package com.ykh.mybbsdemo.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykh.mybbsdemo.constant.ArticleConstant;
import com.ykh.mybbsdemo.constant.ArticleStatusEnum;
import com.ykh.mybbsdemo.dao.dos.Archives;
import com.ykh.mybbsdemo.dao.mapper.ArticleBodyMapper;

import com.ykh.mybbsdemo.dao.mapper.ArticleMapper;
import com.ykh.mybbsdemo.dao.mapper.ArticleTagMapper;
import com.ykh.mybbsdemo.dao.mapper.WmSensitiveMapper;
import com.ykh.mybbsdemo.dao.pojo.po.*;
import com.ykh.mybbsdemo.dao.pojo.vo.*;
import com.ykh.mybbsdemo.service.*;
import com.ykh.mybbsdemo.util.RedisUtil;
import com.ykh.mybbsdemo.util.SensitiveWordUtil;
import com.ykh.mybbsdemo.util.UserThreadLocal;
import com.ykh.mybbsdemo.dao.pojo.dto.ArticleParam;
import com.ykh.mybbsdemo.dao.pojo.dto.PageParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2023-06-03
 * Time: 20:57
 */
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    ThreadService threadService;
    @Autowired
    WmSensitiveMapper wmSensitiveMapper;
    @Resource
    RedisUtil redisUtil;

    /**
     * 文章列表分页查询
     *
     * @param pageParams
     * @return
     */
    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = this.articleMapper.listArticle(page, pageParams.getCategoryId(), pageParams.getTagId(), pageParams.getYear(), pageParams.getMonth());
        return Result.success(copyList(articleIPage.getRecords(), true, true));
    }


//    /**
//     * 最热文章
//     * @param limit
//     * @return
//     */
//    @Override
//    public Result hotArticle(int limit) {
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        //根据浏览量排序
//        queryWrapper.orderByDesc((Article::getViewCounts));
//        queryWrapper.select(Article::getId, Article::getTitle);
//        queryWrapper.eq(Article::getState, 1);
//        queryWrapper.last("limit " + limit);
//        //以上语句对应sql : select id,title from article order by view_counts desc limit 5;
//        List<Article> articles = articleMapper.selectList(queryWrapper);
//        //将查询结果转换成josn数据
//        String hotArticle = redisUtil.get(ArticleConstant.HOT_ARTICLE_FIRST_PAGE);
//        List<Article> hotArticleList = JSON.parseObject(hotArticle, new TypeReference<List<Article>>(){});
//        return Result.success(copyList(hotArticleList, false, false));
//    }

    /**
     *  从Redis中取出最热文章
     * @return
     */
    @Override
    public Result hotArticle()  {
        //将查询结果转换成josn数据
        String hotArticle = redisUtil.get(ArticleConstant.HOT_ARTICLE_FIRST_PAGE);
        List<Article> hotArticleList = JSON.parseObject(hotArticle, new TypeReference<List<Article>>(){});
        return Result.success(copyList(hotArticleList, false, false));
    }

    /**
     * 最新文章
     *
     * @param limit
     * @return
     */
    @Override
    public Result newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.eq(Article::getState, 1);
        queryWrapper.last("limit " + limit);
        //对应的sql : select id,title from article order by create_date desc limit 5;
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));
    }

    /**
     * 文章归档
     */
    @Override
    public Result listArchives() {
        List<Archives> archiveslist = articleMapper.listArchives();
        return Result.success(archiveslist);
    }

    /**
     * 查看文章详情
     */
    @Override
    public Result findArticleById(long articleId) {
        /**
         * 1. 根据ID查询文章信息
         * 2. 根据bodyId 和 categoryId 做一个关联查询
         */
        //先根据文章ID查找到对应文章
        Article article = this.articleMapper.selectById(articleId);
        //将文章转化为对应的ArticleVo类
        ArticleVo articleVo = copy(article, true, true, true, true);
        //查找文章后, 要更新阅读数 ,此处要添加一个更新阅读数的操作,更新时加 写的锁,会影响程序的性能
        //使用一个线程池, 保证 这个更新阅读数的操作不影响主线程的运行,同时如果更新操作出现问题,不影响查看文章的操作
        //线程池
        threadService.updateArticleViewCount(articleMapper, article);
        return Result.success(articleVo);
    }

    /**
     * 发布文章
     *
     * @param articleParam
     * @return
     */
    @Override
    @Transactional
    public Result publish(ArticleParam articleParam) {
        //获取当前用户,需要在拦截中添加该接口,允许当前接口访问
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 其实就是 -> 构建Article对象
         * 2. 作者id -> 当前登录的用户
         * 3. 将标签加到标签与文章的关联列表中
         * 4. 将文章内容插入到文章内容的的表中
         * 5. 将设置完的article更新到数据库
         * 6. 对文章内容进行敏感词过滤
         */
        //判断是否为修改文章
        if(articleParam.getId() != null){
            return updateArticle(articleParam);
        }
        //1.创建一个新的文章对象
        Article article = new Article();
        //2.设置当前文章的作者
        article.setAuthorId(sysUser.getId());
        //设置其他属性
        article.setWeight(0);
        article.setViewCounts(Article.Article_Common);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(Article.Article_Common);
        article.setCreateDate(LocalDateTime.now());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));

        //判断是否为草稿
        if(articleParam.getState()!=null && articleParam.getState().equals(ArticleStatusEnum.IS_DRAFT.getCode())){
            article.setState(ArticleStatusEnum.IS_DRAFT.getCode());
        } else {
            article.setState(ArticleStatusEnum.NO_PUBLISH.getCode());
        }

        //3.将新增的标签加到标签与文章的关联列表中
        //要先有文章的id , 先将当前新文章插入,插入后就会生成一个文章id
        this.articleMapper.insert(article);
        //获取当前的tag的id
        List<TagVo> tags = articleParam.getTags();
        //判断是否有效,有效就进行设置
        if (tags != null) {
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                //设置文章id
                articleTag.setArticleId(articleId);
                //设置标签id
                articleTag.setTagId(Long.parseLong(tag.getId()));
                //插入数据库
                this.articleTagMapper.insert(articleTag);
            }
        }

        //4.新发布文章的内容存储+*
        //先要有文章体的Id
        ArticleBody articleBody = new ArticleBody();
        //设置文章内容的Id为当前文章的id
        articleBody.setArticleId(article.getId());
        //设置新发布文章的内容到文章内容中
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        //将当前文章内容插入数据库, 便能得到一个文章体的Id
        articleBodyMapper.insert(articleBody);
        //此时就可以,设置article中的body_id了
        article.setBodyId(articleBody.getId());
        //6. 对文章内容进行敏感词过滤
        Map<String, Integer> sensitiveWordMap = handleFilter(articleBody.getContent());
        if(!sensitiveWordMap.isEmpty()){
            //包含敏感词
            article.setState(ArticleStatusEnum.PUBLISH_FAIL.getCode());
            article.setReason("文章包含敏感词" + sensitiveWordMap);
            log.info("文章包含敏感词" + sensitiveWordMap);
        }else {
            article.setState(ArticleStatusEnum.PUBLISH_SUCCESS.getCode());
        }
        //5. atricle的所有属性设置完,将其更新到数据库中
        articleMapper.updateById(article);
        //根据接口要求的返回对象类型,返回数据
        Map<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    /**
     * 敏感词审核
     * @param content
     */
    @Async
    public  Map<String, Integer> handleFilter(String content) {
        //获取所有敏感词
        List<WmSensitive> wmSensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>query().select("sensitives"));
        List<String> collect = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(collect);
        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        return map;
    }

    /**
     * 发布文章时更新文章
     * @param articleParam
     * @return
     */
    private Result updateArticle(ArticleParam articleParam) {
        Article article = new Article();
        //查询出文章
        LambdaQueryWrapper<Article> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Article::getId, articleParam.getId());
        Article article1 = articleMapper.selectOne(queryWrapper1);
        article1.setId(articleParam.getId());
        article1.setTitle(articleParam.getTitle());
        article1.setSummary(article.getSummary());
        article1.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article1.setState(0);
        //查询出文章内容
        LambdaQueryWrapper<ArticleBody> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(ArticleBody::getId,article1.getBodyId());
        ArticleBody articleBody = articleBodyMapper.selectOne(queryWrapper2);
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());

        //更新数据库文章内容和文章信息
        articleMapper.update(article1, queryWrapper1);
        articleBodyMapper.update(articleBody, queryWrapper2);
        return Result.success("修改成功");
    }


    /**
     * 转换数据库类型数据为 josn数据
     *
     * @param records
     * @param isTag
     * @param isAuthor
     * @return
     */
    //转型转换
    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        //循环进行转换
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, false, false));
        }
        return articleVoList;
    }

    //转型转换
    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody, boolean isCaregary) {
        //循环进行转换
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, isBody, isCaregary));
        }
        return articleVoList;
    }

    //转换单条数据
    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        //Spring 提供的复制属性的方法, 将数据库类型的数据,复制到articlevo中
        BeanUtils.copyProperties(article, articleVo);

        //处理日期的字段
        articleVo.setCreateDate(article.getCreateDate());
        //并不是所有的接口 都需要标签和作者信息,通过isTag 和 isAuthor进行判断这个文章对象是否需要
        if (isTag) {
            //根据文章的id找到对应的标签, 设置到articleVo对象中
            articleVo.setTags(tagService.findTagsByArticleId(article.getId()));
        }

        if (isAuthor) {
            Long authorId = article.getAuthorId();
            SysUser sysUser = sysUserService.findUserById(authorId);
            UserVo userVo = new UserVo();
            userVo.setAvatar(sysUser.getAvatar());
            userVo.setNickname(sysUser.getNickname());
            userVo.setId(String.valueOf(sysUser.getId()));
            articleVo.setAuthor(userVo);
        }

        if (isBody) {
            //根据bodyID, 查询body的信息
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }

        if (isCategory) {
            //根据CategoryId, 查询category的信息
            Long categoryId = article.getCategoryId();
            articleVo.setCategorys(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }


    /**
     * 根据文章body的id查找文章
     *
     * @param bodyId
     * @return
     */
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

    /**
     * 获取当前的登录的用户的文章
     *
     * @param sysUser
     * @return
     */
    @Override
    public Result getMyArticle(PageParams pageParams, SysUser sysUser) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = this.articleMapper.getMyArticle(sysUser.getId(), page, pageParams.getCategoryId(), pageParams.getTagId(), pageParams.getYear(), pageParams.getMonth());
        return Result.success(copyList(articleIPage.getRecords(), true, true));

    }

    /**
     * 用户删除文章
     * @param id
     * @return
     */
    @Override
    public Result deleteById(long id) {
        articleMapper.deleteById(id);
        return Result.success("删除成功");
    }

    @Override
    public Result likeArticle(String quary) {
       List<Article> articleList = articleMapper.likeArticle(quary);
       return Result.success(copyList(articleList, true,true));
    }

    //    /**
//     * 用户修改文章
//     *
//     * @return
//     */
//
//    public Result updateArticle(ArticleVo articleVo) {
//        Long articleId = Long.valueOf(articleVo.getId());
//        Article article = this.articleMapper.selectById(articleId);
//        article.setSummary(articleVo.getSummary());
//        article.setTitle(articleVo.getTitle());
//        article.setCreateDate(LocalDateTime.now());
//
//        //根据文章Id 查出文章内容
//        LambdaQueryWrapper<ArticleBody> queryWrapper1 = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<Article> queryWrapper2 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(ArticleBody::getArticleId, article.getId());
//        queryWrapper2.eq(Article::getId, article.getId());
//
//        ArticleBody articleBody = articleBodyMapper.selectOne(queryWrapper1);
//        //修改新的内容给文章内容
//        articleBody.setContent(articleVo.getBody().getContent());
//        articleBodyMapper.update(articleBody, queryWrapper1);
//        articleMapper.update(article,queryWrapper2);
//        return Result.success("修改成功");
//    }


}
